<?php
class Admin_UsersController extends Zend_Controller_Action
{		
	public function logoutAction()
	{
		// after log out, redirect to homepage regardless of what role the user has.
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();		
		return $this->_redirect('/admin');
	}
	
	public function createAction()
	{
		$userForm = new Admin_Form_Users();
		$userForm->setAction('/admin/users/create')->setMethod('post');

		$userForm->addRoleCheckboxes();
		
		if($this->_request->isPost()) {
			if($userForm->isValid($_POST)) {	
				$data = $userForm->getValues();	
				
				// get role array from RoleIDIsCheckedMap
				$roleModel = new Admin_Model_Role();
				$roles = $roleModel->getRoleIDsFromRoleIDIsCheckedMap($data['roles']);
				
				// create user account
				$userModel = new Admin_Model_Users();			
				try {
					$user = $userModel->createUserAccount(
						$data['newUsername'],
						$data['password'], 
						null,
						$roles
					);					
				} catch(Exception $e) {
					return TBB_Utility_Redirector::redirect($e->getMessage(), 'admin', 'error', 'fatal-error');									
				}
				return $this->_redirect('/admin/users/list');				
			}
		}		
		$this->view->createForm = $userForm;
	}
	
	public function updateAction()
	{
		$userForm = new Admin_Form_Users();
		$userForm->setAction('/admin/users/update')->setMethod('post');	
		$userForm->disableUsernameInput();
		$userForm->disableRequiredOnPassword();
		
		if($this->_request->isPost()) {
			// get params from $_POST	
			$id = $this->_request->getParam('user_id');			
			$isPasswordChanged = $this->_request->getParam('isPasswordChanged');
			$roles = $this->_request->getParam('roles');

			if($userForm->isValid($_POST)) {
				$userData = $userForm->getValues();
				$userModel = new Admin_Model_Users();
				
				$userModel->updateUser(
					$userData['user_id'],
					$userData['newUsername'],
					$userData['password'],
					$isPasswordChanged
				);
				
				$roleModel = new Admin_Model_Role();
				$roleIDs = $roleModel->getRoleIDsFromRoleIDIsCheckedMap($roles);
				$userModel->updateRolesOfUser($roleIDs, $id);
				return $this->_redirect('/admin/users/list');
			}
		} else {
			// get userID from link you clicked
			$id = $this->_request->getParam('id');						
		}
		
		// populate the fields we need
		$userModel = new Admin_Model_Users();
		$userRow = $userModel->find($id)->current();
		
		// populate form
		$userForm->getElement('user_id')->setValue($userRow['user_id']);
		$userForm->getElement('newUsername')->setValue($userRow['username']);

		// add some needed to form
		$userForm->addIsPasswordChangedCheckbox();
		$userForm->addRoleCheckboxes($id);	
		
		$this->view->form = $userForm;
	}
	
	public function deleteAction()
	{
		$id = $this->_request->getParam('id');
		$userModel = new Admin_Model_Users();
		$userModel->deleteUser($id);
		$this->_redirect('/admin/users/list');
	}
	
	public function listAction()
	{		
		$userModel = new Admin_Model_Users();
		$userArray = $userModel->getUserArray();

		// add roles to each user		
		$userArray = $userModel->addRolesToUserArray($userArray);
		
		if(count($userArray) > 0) {
			$paginator = Zend_Paginator::factory($userArray);
			$page = $this->_request->getParam('page', 1);
			$paginator->setItemCountPerPage(5);
			$paginator->setCurrentPageNumber($page);
			$this->view->paginator = $paginator;			
		}	
	}
	
	public function loginAction()
	{
		$userForm = new Admin_Form_UserLogin();
		$userForm->setMethod('post')->setAction('/admin/users/login');

		if($this->_request->isPost()) {			
			if($userForm->isValid($_POST)) {
				$userData = $userForm->getValues();
				
				//////////////////////// Authentication /////////////////////////				
				$adapter = new TBB_Auth_Adapter2($userData['username'], $userData['password']);	
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($adapter);
				if($result->getCode() == Zend_Auth_Result::SUCCESS) {			 
					// redirect to module customer regardless of what role the user has
					return $this->_redirect('/admin');
				} else { // when login fails
					$this->view->loginMessage = "Sorry, you username or password is incorrect.";					
				}
				/////////////////////////////////////////////////////////////////
			} else { // when POST data is invalid, this case happens when any of fields in form is empty or invalid. 
				
			}
		}		
		$this->view->moduleName = $this->_request->getModuleName();
		$this->view->form = $userForm;
	}
	
	public function indexAction()
	{
		
	}	
}